import { DarkTheme, DefaultTheme, ThemeProvider } from '@react-navigation/native';
import { Stack, usePathname, useRootNavigationState, useRouter, useSegments } from 'expo-router';
import { StatusBar } from 'expo-status-bar';
import { useEffect, useRef } from 'react';
import 'react-native-reanimated';
import { BackHandler, Platform, ToastAndroid } from 'react-native';
import { SafeAreaProvider } from 'react-native-safe-area-context';

import { AuthProvider, useAuth } from '@/context/auth-context';
import { useColorScheme } from '@/hooks/use-color-scheme';

function RootNavigator() {
  const { user, isAuthenticated, isRestoring, viewMode } = useAuth();
  const navigationState = useRootNavigationState();
  const segments = useSegments();
  const router = useRouter();
  const pathname = usePathname();
  const lastBackPressRef = useRef(0);

  useEffect(() => {
    if (!navigationState?.key || isRestoring) {
      return;
    }

    if (!isAuthenticated) {
      return;
    }

    const primarySegment = segments[0];
    const merchantHome = '/(merchant)/overview';
    const customerHome = '/(tabs)';
    const role = viewMode ?? (user?.channel ?? 'customer');
    const defaultPath = role === 'merchant' ? merchantHome : customerHome;

    if (primarySegment === '(auth)') {
      router.replace(defaultPath);
      return;
    }
    // 按“仅按钮切换”约定：不做任何自动重定向，
    // 用户可在任意端自由浏览，由切换入口决定落点。
  }, [isAuthenticated, isRestoring, navigationState?.key, router, segments, user, viewMode]);

  useEffect(() => {
    const subscription = BackHandler.addEventListener('hardwareBackPress', () => {
      const isOnHome =
        pathname === '/' ||
        pathname === '/(tabs)' ||
        pathname === '/(merchant)' ||
        pathname === '/(merchant)/overview';

      if (!isOnHome) {
        if (router.canGoBack()) {
          router.back();
        } else {
          const fallback = user?.channel === 'merchant' ? '/(merchant)/overview' : '/(tabs)';
          router.replace(fallback);
        }
        return true;
      }

      const now = Date.now();
      if (now - lastBackPressRef.current < 400) {
        BackHandler.exitApp();
        return true;
      }

      lastBackPressRef.current = now;
      if (Platform.OS === 'android') {
        ToastAndroid.show('再次按下返回键即可退出应用', ToastAndroid.SHORT);
      }
      return true;
    });

    return () => subscription.remove();
  }, [pathname, router, user?.channel]);

  return (
    <Stack screenOptions={{ headerShown: false }} initialRouteName="(tabs)">
      <Stack.Screen name="(auth)" options={{ headerShown: false }} />
      <Stack.Screen name="(tabs)" options={{ headerShown: false }} />
      {/* C 端商品详情页使用独立前缀，避免与商户编辑冲突 */}
      <Stack.Screen name="c/product/[id]" options={{ headerShown: false }} />
      <Stack.Screen name="(merchant)" options={{ headerShown: false }} />
      <Stack.Screen
        name="modal"
        options={{ presentation: 'modal', title: 'Modal', headerShown: true }}
      />
    </Stack>
  );
}

export default function RootLayout() {
  const colorScheme = useColorScheme();

  return (
    <AuthProvider>
      <ThemeProvider value={colorScheme === 'dark' ? DarkTheme : DefaultTheme}>
        <SafeAreaProvider>
          <RootNavigator />
          <StatusBar style="auto" />
        </SafeAreaProvider>
      </ThemeProvider>
    </AuthProvider>
  );
}

